<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    <link rel="stylesheet" href="./asset/bootstrap@5.3.0/css/bootstrap.min.css">
</head>
<body>
    <!-- 导航条 -->
    <nav class="navbar navbar-expand-lg bg-primary">
        <div class="container-fluid">
          <a class="navbar-brand" href="#">Navbar</a>
          <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
              <li class="nav-item">
                <a class="nav-link active" aria-current="page" href="#">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
              </li>
              <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                  Dropdown
                </a>
                <ul class="dropdown-menu">
                  <li><a class="dropdown-item" href="#">Action</a></li>
                  <li><a class="dropdown-item" href="#">Another action</a></li>
                  <li><hr class="dropdown-divider"></li>
                  <li><a class="dropdown-item" href="#">Something else here</a></li>
                </ul>
              </li>
              <li class="nav-item">
                <a class="nav-link disabled">Disabled</a>
              </li>
            </ul>
            <form class="d-flex" role="search">
              <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
              <button class="btn btn-outline-success" type="submit">Search</button>
            </form>
          </div>
        </div>
      </nav>
    <!-- \导航条 -->

    <!-- 表单 -->
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-8 col-lg-4">
                <div class="card">

                    <div class="card-body">
                        <form id="registForm" novalidate="novalidate">
                            <div class="mb-3">
                              <label for="emailInput" class="form-label">Email address</label>
                              <input type="email" class="form-control" id="emailInput" aria-describedby="emailHelp">
                              <div id="emailHelp" class="form-text"></div>
                            </div>
                            <div class="mb-3">
                                <label for="nickNameInput" class="form-label">nickName</label>
                                <input type="text" class="form-control" id="nickNameInput" aria-describedby="nickNameHelp">
                                <div id="nickNameHelp" class="form-text"></div>
                            </div>
                            <div class="mb-3">
                                <label for="pwdInput" class="form-label">password</label>
                                <input type="password" class="form-control" id="pwdInput" aria-describedby="pwdHelp">
                                <div id="pwdHelp" class="form-text"></div>
                            </div>
                            <div class="mb-3">
                              <label for="repwdInput" class="form-label">rePassword</label>
                              <input type="password" class="form-control" id="repwdInput">
                            </div>
                            <button type="submit" id="registBtn" class="btn btn-primary d-block w-100">注册</button>
                            <a class="btn btn-primary d-block w-100" href="login.html">返回登录</a>
                        </form>
                </div>
            </div>
            </div>
        </div>
    </div>

    <!-- \表单 -->

    <script src="./asset/just-validate@4.3.0/just-validate.production.min.js"></script>
    <script src="./asset/bootstrap@5.3.0/js/bootstrap.bundle.min.js"></script>

    <script>
        const validate = new JustValidate('#registForm',{
            errorFieldCssClass: 'is-invalid',
            errorLabelStyle: {
                fontSize: '14px',
                color: '#dc3545',
            },
            successFieldCssClass: 'is-valid',
            successLabelStyle: {
                fontSize: '14px',
                color: '#20b418',
            },
            focusInvalidField: false,
            validateBeforeSubmitting: true,
            lockForm: true,
        });

        //validator.showErrors({ '#emailInput': '邮箱不能为空' });

        validate.addField("#emailInput",[{
                rule: 'required',
                errorMessage: '邮箱不能为空！'
            },
            {
                rule: 'email',
                errorMessage: '请输入正确的邮箱格式'
            }]).addField("#nickNameInput",[{
                rule: 'required',
                errorMessage: '昵称不能为空'
            }]).addField('#pwdInput', [
               {
                rule: 'required',
                errorMessage: '密码不能为空'
               },
            ]).addField('#repwdInput', [
                {
                    rule: 'required',
                    errorMessage: '重复密码不能为空'
                },
                {
                    validator: (value, fields) => {
                        if (
                            fields['#pwdInput'] && fields['#pwdInput'].elem
                        ) {
                            const repeatPasswordValue = fields['#pwdInput'].elem.value;
                            return value === repeatPasswordValue;
                        }
                        return true;
                    },
                    errorMessage: '两次密码必须一致',
                },
            ]);
        //验证邮箱是否存在
        document.querySelector('#emailInput')?.addEventListener('blur', () => {
             validate.revalidateField("#emailInput").then(isValid=>{
                 let flag =false;
                  if(isValid){
                      let value=  document.querySelector('#emailInput').value;
                      fetch("/checkEmail?email="+value ).then(response => response.json())
                          .then(data => {
                              console.log( data);
                              if(data.flag){
                                  validate.showSuccessLabels({
                                      '#emailInput': '可以使用',
                                  });
                                  flag=true;
                              }else{
                                  validate.showErrors({
                                      '#emailInput': '邮箱已存在!',
                                  });
                                  flag= false;
                              }
                          });
                  }
                  return false;
            })
        });

        //提交数据
        validate.onSuccess((event) => {
           // event.preventDefault();
            console.log(event)

            //获得表单的数据
            let email=document.querySelector("#emailInput").value;
            let pwd=document.querySelector("#pwdInput").value;
            let nickName =document.querySelector("#nickNameInput").value;
            //追加数据
            let data={email:email,pwd:pwd,nickName:nickName}
            //执行注册的请求
            fetch("regist",{
                method:"POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body:JSON.stringify(data)
            }).then(response => response.json()).then(data=> {
                console.log(data);
            } )
        });


    </script>
</body>
</html>